﻿namespace Blaze.Editor
{
    using System;
    using System.IO;
    using System.Text;
    using Framework;
    using UnityEngine;

    /// <summary>
    /// 用于调整文件的编码。
    /// </summary>
    public static class EncodingConverter
    {
        /// <summary>
        /// 批处理指定目录以及其所有子目录下的文件。
        /// </summary>
        /// <param name="filePaths">文件路径</param>
        /// <param name="encoding">编码</param>
        /// <returns>已处理的文件数组</returns>
        public static void BatchProcess(string[] filePaths, Encoding encoding)
        {
            for (var i = 0; i < filePaths.Length; i++)
            {
                try
                {
                    Process(filePaths[i], encoding);
                }
                catch (Exception e)
                {
                    Debug.Log("Failed to convert " + filePaths[i] + ":" + e);
                }
            }
        }

        /// <summary>
        /// 将指定文件处理为指定的编码。
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="encoding">编码</param>
        public static void Process(string filePath, Encoding encoding)
        {
            var bytes = File.ReadAllBytes(filePath);
            var detectedEncoding = mDetector.DetectEncoding(bytes,bytes.Length);
            Encoding originalEncoding;
            switch (detectedEncoding)
            {
                case TextEncodingDetect.Encoding.None:
                    return;
                case TextEncodingDetect.Encoding.Ansi:
                    originalEncoding = EncodingExtension.GB2312;
                    break;
                case TextEncodingDetect.Encoding.Ascii:
                    originalEncoding = Encoding.ASCII;
                    break;
                case TextEncodingDetect.Encoding.Utf8Bom:
                    originalEncoding = Encoding.UTF8;
                    break;
                case TextEncodingDetect.Encoding.Utf8Nobom:
                    originalEncoding = new UTF8Encoding(false);
                    break;
                case TextEncodingDetect.Encoding.Utf16LeBom:
                case TextEncodingDetect.Encoding.Utf16LeNoBom:
                case TextEncodingDetect.Encoding.Utf16BeBom:
                case TextEncodingDetect.Encoding.Utf16BeNoBom:
                    return;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            var content = File.ReadAllText(filePath, originalEncoding);
            File.WriteAllText(filePath, content, encoding);
        }

        private static readonly TextEncodingDetect mDetector = new TextEncodingDetect();
    }
}